package middle;

import java.util.ArrayList;
import java.util.List;

public class Solution_216 {
    private int count;
    private List<List<Integer>> rst;
    private boolean[] flags = new boolean[10];
    public List<List<Integer>> combinationSum3(int k, int n) {
        this.count = k;
        this.rst = new ArrayList<>();
        dps(new ArrayList(), 1, 0, n);
        return rst;
    }

    private void dps(List<Integer> list, int index, int num, int target) {
        if (num == target) {
            if (list.size() == count) {
                rst.add(new ArrayList(list));
            }
            return;
        }
        for (int i = index; i < flags.length; i++) {
            if (!flags[i] && num + i <= target) {
                flags[i] = true;
                list.add(i);
                dps(list, i + 1, num + i, target);
                list.remove(list.size() - 1);
                flags[i] = false;
            }
        }
    }

    public static void main(String[] args) {
        Solution_216 model = new Solution_216();
        System.out.println(model.combinationSum3(3, 7));
        System.out.println(model.combinationSum3(3, 9));
        System.out.println(model.combinationSum3(4, 1));
    }
}
